﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Win.Common;
using Win.Model;

namespace Win.DAL
{
    public class UserDAL
    {
        //访问数据库
        DbContext dbContext = new db0Entities1();

        public user GetUser(string username,string passwd)
        {
            return dbContext.Set<user>().Where(u => (u.username.Equals(username) && u.passwd.Equals(passwd))).FirstOrDefault();
        }

        public List<user> GetList()
        {
            DbSet<user> users = dbContext.Set<user>();
            List<user> list = new List<user>(users);
            return list;
        }

        public void AddUser(string username, string passwd)
        {
            user u = new user(username, passwd);
            dbContext.Entry<user>(u).State = EntityState.Added;
            dbContext.SaveChanges();
        }

        public user GetUserById(int id)
        {
            return dbContext.Set<user>().Where(u => u.id == id).FirstOrDefault();
        }

        public void DelUser(int id) 
        {
            user u = GetUserById(id);
            dbContext.Entry<user>(u).State = EntityState.Deleted;
            dbContext.SaveChanges();
        }

        public void UpdateUser()
        {
            var entity = dbContext.Set<user>().Single(u => u.username == "user01"); 
            entity.username = "user";
            dbContext.Set<user>().Attach(entity);
            dbContext.Entry(entity).Property(a => a.username).IsModified = true; 
            dbContext.SaveChanges();
        }
    }
}
